package com.itheima.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dto.OrderDto;
import com.itheima.entity.*;
import com.itheima.mapper.*;
import com.itheima.service.OrdersService;
import com.itheima.utils.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired(required = false)
    private OrderMapper orderMapper;

    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;

    @Autowired(required = false)
    private OrderDtoMapper orderDtoMapper;

    /**
     * 作用： 下单
     *
     * @param orders 订单的信息（地址id，支付方式，备注）
     * @return
     * @Param userId  当前的登陆者
     */
    @Override
    public void submit(Orders orders, long userId) {
//        A. 获得当前用户id, 查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.fincartByUserId(userId);

        //        B. 根据当前登录用户id, 查询用户数据
        User user1 = userMapper.findById(userId);

//        C. 根据地址ID, 查询地址数据
        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
//订单的id
        long orderId = UUIDUtils.getUUIDInOrderId().longValue();

        //声明变量记录总金额
        BigDecimal totalAmount = new BigDecimal("0");

//        D. 遍历所有的购物像， 一个购物项就是一个订单明细， 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setId(UUIDUtils.getUUIDInOrderId().longValue());//订单项目的主键
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setOrderId(orderId);//订单项所属的订单的id
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetail.setImage(shoppingCart.getImage());

            //计算每一个购物项的总价
            BigDecimal multiply = shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber() + ""));
            totalAmount = totalAmount.add(multiply);
            orderDetailList.add(orderDetail);
        }
        //        E. 组装订单数据, 批量保存订单数据
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setStatus(1);
        orders.setUserId(userId);

        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(totalAmount);

        orders.setUserName(user1.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());

        orderMapper.save(orders);

        orderDetailMapper.saveBatch(orderDetailList);

    }

    @Override
    public Page<Orders> page(Integer page, Integer pageSize, String number,String beginTime,String endTime) {
        PageHelper.startPage(page,pageSize);

      List<Orders> ordersList= orderMapper.findAllOrNumberOrOrderTime(number,beginTime,endTime);

        PageInfo<Orders> ordersPageInfo=new PageInfo<>(ordersList);

        Page<Orders> ordersPage=new Page<>(ordersPageInfo.getList(),ordersPageInfo.getTotal(),page,pageSize);

        return ordersPage;

    }

    @Override
    public Page<OrderDto> userPage(Integer page, Integer pageSize,Long userId) {
       Long pages= orderMapper.count(userId);
        PageHelper.startPage(page,pageSize);
        List<Orders> ordersList=orderMapper.findAll(userId);
        PageInfo<Orders> ordersPageInfo =new PageInfo<>(ordersList);

        //创建空的orderdto接收
        List<OrderDto> orderDtoList=new ArrayList<>();
        //遍历pageinfo，把补全orderdto
        for (Orders orders : ordersPageInfo.getList()) {
         List<OrderDetail> orderDetails=   orderDetailMapper.findbyId(orders.getId());
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(orders,orderDto);
            orderDto.setOrderDetails(orderDetails);
           orderDtoList.add(orderDto);


        }
        Page<OrderDto> ordersPage=new Page<>(orderDtoList,ordersPageInfo.getTotal(),pageSize,page);
        return ordersPage;
    }

    @Override
    public OrderDto again(OrderDto orderDto) {
//        OrderDto orderDtoNew = new OrderDto();
//        List<Orders> ordersList=orderMapper.findAll(orderDto.getUserId());
//        for (Orders orders : ordersList) {
//
//            BeanUtils.copyProperties(orders,orderDtoNew);
//            List<OrderDetail> orderDetails=   orderDetailMapper.findbyId(orders.getId());
//            orderDtoNew.setOrderDetails(orderDetails);
//        }

        ShoppingCartServiceImpl shoppingCartService = new ShoppingCartServiceImpl();
        //找到
        //1. 根据用户的id与dish_id 或者setmeal_id查看购物车表是否存在该购物项
//        ShoppingCart shoppingCartnew = shoppingCartMapper.findUidAndDidAndSid(shoppingCart);
//        //如果没找到就添加进去
//        if (shoppingCartnew == null) {
//            shoppingCart.setCreateTime(LocalDateTime.now());
//            shoppingCart.setNumber(1);
//            shoppingCartMapper.save(shoppingCart);
//            shoppingCartnew = shoppingCart;
//        } else {
//            //如果已经存在，则数量加一
//            shoppingCartnew.setNumber(shoppingCartnew.getNumber() + 1);
//            shoppingCartMapper.update(shoppingCartnew);
//        }
//        return orderDtoNew;
//    }
//}
        return  null;
    }
}